from django.contrib.auth.hashers import check_password
from django.http import HttpResponse
from django.shortcuts import render, redirect

# Create your views here.
from app.models import User


def login(request):
    # print(request.method)
    if (request.method == "GET"):
        return render(request, "app/login.html")
    elif (request.method == "POST"):
        username = request.POST.get("username")
        password = request.POST.get("password")

        stu = User.objects.filter(username=username)
        password1 = stu[0].password
        # 解密
        isTrue = check_password(password, password1)
        if isTrue and stu:
            print("通过")
            # 存储session
            request.session["user_session"] = username
            return redirect("/home")
        else:
            print("err")
            return render(request, "index.html")


def register(request):
    if (request.method == "GET"):
        return render(request, "app/register.html")

    elif (request.method == "POST"):
        username = request.POST.get("username")
        password = request.POST.get("password")
        password1 = request.POST.get("password1")

        if password != password1:
            print("密码err")
            return redirect("user/login")
        else:
            stu = User.objects.filter(username=username)
            # 用户已存在
            if stu:
                print("用户已经存在")
                return redirect("user/register")
            else:
                # form = RegisterForm(request.POST)
                return HttpResponse("ok")
                


def home(request):
    return None
